<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { CheckboxValueType, FormInstance, FormRules } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import type { UserInfo } from '@/api/login/type'
import { addUser, paginationQuery, assignRoleRequest, deleteUsersRequest } from '@/api/user'
import type { PageNationParams } from '@/api/user/type'
import { queryRoleList } from '@/api/role'
import type { Role } from '@/api/role/type'
import { useUserStore } from '@/stores/userStore'

// 搜索用到的用户名
const ruleForm = reactive({ username: '' })
// 搜索表单实例
const searchFormRef = ref<FormInstance>()
// 抽屉显示控制符
const drawer = ref(false)
// 表单校验规则
const searchRules = reactive<FormRules>({
  username: [{ required: false, message: '用户名不能为空', trigger: 'blur' }],
})
// 搜索按钮单击事件
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // 校验通过再发送请求
  formEl.validate(async (valid, fields) => {
    if (valid) {
      pageNationParams.condition = ruleForm.username
      await paginationQuery(pageNationParams).then((res) => {
        userInfoList.value = res.items
        count.value = res.count
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 重置搜索框单击事件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 添加按钮单击事件
const openDrawer = () => (drawer.value = true)
// 定义用户变量
const userInfo = reactive<UserInfo>({
  userId: 0,
  username: '',
  password: '',
  avatar: '',
  token: '',
  roles: [],
  permissions: [],
  buttons: [],
})
// 用户表单实例
const confirmFormRef = ref<FormInstance>()
// 用户表单校验规则
const userRules = reactive<FormRules>({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, max: 50, message: '长度在5到50之间', trigger: 'change' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 5, max: 50, message: '长度在5到50之间', trigger: 'change' },
  ],
})
// 确定按钮单击事件
const confirmClick = async () => {
  // 校验通过再发送请求
  await confirmFormRef.value.validate(async (valid) => {
    if (valid) {
      await addUser(userInfo)
        // 若添加成功，则隐藏抽屉,并重新查询用户信息
        .then(
          async (res) => (
            (drawer.value = false),
            await paginationQuery(pageNationParams).then((res) => {
              userInfoList.value = res.items
              count.value = res.count
            })
          ),
        )
        .catch((err) => {
          console.log(err)
        })
    }
  })
}
// 取消按钮单击事件
const cancelClick = () => {
  // 隐藏抽屉
  drawer.value = false
  roleDrawer.value = false
  roles.value = []
  // 清空数据
  ;(userInfo.username = undefined), (userInfo.password = undefined)
}
// 分页查询参数
const pageNationParams = reactive<PageNationParams>({ pageIndex: 1, pageSize: 5, condition: '' })
// 用户信息集合
const userInfoList = ref<UserInfo[]>([])
// 页面加载之后先进行查询
onMounted(async () => {
  await paginationQuery(pageNationParams).then((res) => {
    userInfoList.value = res.items
    count.value = res.count
  })
})
// 分配角色抽屉控制符 true-显示;false-隐藏
const roleDrawer = ref(false)
// 角色对象，里面存放全部角色信息
const roleList = ref<Role[]>([])
//
const userVo = ref<UserInfo>({
  userId: 0,
  username: '',
  avatar: '',
  token: '',
  password: '',
  roles: [],
  permissions: [],
  buttons: [],
})
// 分配角色按钮单击事件
const assignRoles = async (data: UserInfo) => {
  userVo.value.userId = data.userId
  // 给用户姓名赋值
  userVo.value.username = data.username
  // 弹出抽屉
  roleDrawer.value = true
  // 查询全部权限
  await queryRoleList().then((res) => {
    roleList.value = res
    data.roles.forEach((item) => {
      roles.value.push(item)
    })
  })
}

const checkAll = ref(false)
const isIndeterminate = ref(true)
const roles = ref<string[]>([])
const handleCheckAllChange = (val: CheckboxValueType) => {
  if (val) {
    roleList.value.forEach((item) => {
      roles.value.push(item.name)
    })
  } else {
    roles.value = []
  }
  isIndeterminate.value = false
}
const handleCheckedRolesChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roleList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roleList.value.length
}
// 角色抽屉表单实例
const roleFormRef = ref<FormInstance>()
// 角色抽屉表单校验规则
const roleRules = reactive<FormRules>({
  // roleCheckbox: [{ required: true, message: '角色不能为空', trigger: 'change' }],
})

// 保存角色分配
const saveRoles = async () => {
  userVo.value.roles = []
  // 将选择的角色放入vo中
  roles.value.forEach((item) => {
    userVo.value.roles.push(item)
  })
  await assignRoleRequest(userVo.value.userId, userVo.value.roles).then(async (res) => {
    roleDrawer.value = false
    roles.value = []
    await paginationQuery(pageNationParams).then((res) => {
      userInfoList.value = res.items
      count.value = res.count
    })
  })
}
// 用户id集合
let userIds: number[] = []
// 确认删除按钮单击事件
const confirm = async (userId: number) => {
  userIds = []
  userIds.push(userId)
  // 删除用户信息
  await deleteUsersRequest(userIds)
    .then(async (res) => {
      await paginationQuery(pageNationParams).then((res) => {
        userInfoList.value = res.items
        count.value = res.count
      })
    })
    .catch((err) => {
      console.log(err)
    })
}
// 总条数
let count = ref<number>(0)
// 构造馥选框时触发的事件
const selectionChange = async (data: UserInfo[]) => {
  userIds = []
  // 将勾选到的id放入集合中
  data.forEach((item) => {
    userIds.push(item.userId)
  })
}
// 批量删除用户信息
const batchDelete = async () => {
  if (userIds.length === 0) {
    return
  }
  // 删除用户信息
  await deleteUsersRequest(userIds)
    .then(async (res) => {
      // 删除之后重新查询
      await paginationQuery(pageNationParams).then((res) => {
        userInfoList.value = res.items
        count.value = res.items
      })
    })
    .catch((err) => {
      console.log(err)
    })
}
// 引入用户仓库
const userStore = useUserStore()
const buttons = userStore.buttons
</script>

<template>
  <div class="container">
    <!--    搜索卡片-->
    <el-card class="search-card">
      <el-form class="search-form" ref="searchFormRef" :rules="searchRules" :model="ruleForm">
        <el-form-item label="用户名:" prop="username">
          <el-input placeholder="请输入用户名" v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm(searchFormRef)"
            v-if="buttons?.includes('QueryUser')"
          >
            搜索
          </el-button>
          <el-button @click="resetForm(searchFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
      <!--      抽屉-->
      <el-drawer v-model="drawer" title="添加用户">
        <el-form :model="userInfo" ref="confirmFormRef" :rules="userRules">
          <el-form-item label="用户姓名" prop="username">
            <el-input v-model="userInfo.username" />
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="userInfo.password" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="flex: auto">
            <el-button @click="cancelClick">取消</el-button>
            <el-button type="primary" @click="confirmClick">确定</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
    <!--    用户信息展示卡片-->
    <el-card class="userinfo-card">
      <div>
        <el-button
          type="primary"
          :icon="Plus"
          @click="openDrawer"
          v-if="buttons?.includes('AddUser')"
        >
          添加用户
        </el-button>
        <el-button
          type="primary"
          :icon="Delete"
          @click="batchDelete"
          v-if="buttons?.includes('DeleteUser')"
        >
          批量删除
        </el-button>
      </div>
      <el-scrollbar class="el-scrollbar">
        <el-table border :data="userInfoList" @selection-change="selectionChange">
          <el-table-column type="selection" width="90" align="center" />
          <el-table-column type="index" label="排序" width="90" align="center" />
          <el-table-column label="用户姓名" width="180" align="center" prop="username" />
          <el-table-column prop="roles" label="用户角色" width="180" align="center">
            <template #default="scope">
              <span style="margin: 0 0.25rem" v-for="item in scope.row.roles" :key="item">
                {{ item }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="用户状态" width="100" align="center" />
          <el-table-column label="操作" width="240" align="center">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="assignRoles(scope.row)"
                v-if="buttons?.includes('AssignRole')"
              >
                分配角色
              </el-button>
              <el-popconfirm title="确定要删除该用户吗？?" @confirm="confirm(scope.row.userId)">
                <template #reference>
                  <el-button size="small" type="danger" v-if="buttons?.includes('DeleteUser')">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <el-pagination
        class="el-pagination"
        background
        layout="total, prev, pager, next, jumper"
        :total="count"
      />
    </el-card>
    <!--    分配角色抽屉-->
    <el-drawer class="role-drawer" title="分配用户角色" ref="roleFormRef" v-model="roleDrawer">
      <el-form :rules="roleRules">
        <el-form-item label="用户姓名">
          <el-input disabled :value="userVo.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表" prop="roleCheckbox">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group v-model="roles" @change="handleCheckedRolesChange">
            <el-checkbox
              v-for="(role, index) in roleList"
              :key="index"
              :label="role.name"
              :value="role.name"
            >
              {{ role.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="saveRoles">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style scoped>
.container {
  padding: 1rem;

  .search-card {
    padding-left: 1rem;
    margin-bottom: 1rem;

    .search-form {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .userinfo-card {
    padding: 0 1rem;

    .el-scrollbar {
      margin-top: 1rem;
    }

    .el-pagination {
      margin-top: 1rem;
    }
  }

  .role-drawer {
    .role-name {
      padding: 0 10px;
      background-color: #00152b;
    }
  }
}
</style>
